package org.raymond.iworks.gateway.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.Map;
import java.util.function.Predicate;

@Slf4j
public class ReactiveWebUtil {
    /**
     * 获取IP地址
     *
     * @param exchange
     * @return
     */
    public static String getRemoteAddress(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        Map<String, String> headers = request.getHeaders().toSingleValueMap();
        String unknown = "unknown";
        String ipv4Local = "127.0.0.1";
        String ipv6Local = "0:0:0:0:0:0:0:1";
        String ip = headers.get("X-Forwarded-For");
        Predicate<String> checkIp = str -> str==null||str.length()==0||unknown.equalsIgnoreCase(str);
        if (checkIp.test(ip)) {
            ip = headers.get("Proxy-Client-IP");
        }
        if (checkIp.test(ip)) {
            ip = headers.get("WL-Proxy-Client-IP");
        }
        if (checkIp.test(ip)) {
            ip = headers.get("HTTP_CLIENT_IP");
        }
        if (checkIp.test(ip)) {
            ip = headers.get("HTTP_X_FORWARDED_FOR");
        }
        if (checkIp.test(ip)) {
            ip = headers.get("X-Real-IP");
        }
        if (checkIp.test(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
            /*
            if(ipv4Local.equals(ip) || ipv6Local.equals(ip)){
                try {
                    // 根据网卡取本地ip
                    InetAddress addr = InetAddress.getLocalHost();
                    ip = addr.getHostAddress();
                } catch (UnknownHostException e) {
                    log.error("{}", e.getMessage());
                }
            }*/
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 0) {
            ip = Arrays.stream(ip.split(",")).findFirst().orElse("");
        }
        return ip;
    }
}
